package com.itheima.controller;

import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    //注入
    @Reference
    private OrderSettingService orderSettingService;

    //文件上传
    @RequestMapping("/upload")
    public Result upload(MultipartFile excelFile) {

        try {
            //使用POIUtils解析数据
            List<String[]> excelList = POIUtils.readExcel(excelFile);
            //解析出来的数据，每一条是一个String类型的，现在需要转换成OrderSetting类型
            List<OrderSetting> orderSettings = new ArrayList<>();
            //循环遍历excelList 得到每一行中的数据
            for (String[] strings : excelList) {

                //每一行的第一个数据是日期
                String orderDate = strings[0];
                //每一行的第二个数据是可预约人数
                String number = strings[1];
                //创建一个pojo，把数据放在ordersettings中,日期和可预约人数 需要转换成相应的类型
                orderSettings.add(new OrderSetting(new Date(orderDate), Integer.parseInt(number)));
            }
            //通过dubbo远程调用服务实现数据批量导入到数据库
            orderSettingService.add(orderSettings);
        } catch (Exception e) {
            e.printStackTrace();
            //文件解析失败
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    @RequestMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(String date) {
        try {
            List<Map> leftObj = orderSettingService.getOrderSettingByMonth(date);
            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS, leftObj);
        } catch (Exception e) {
            return new Result(true, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    @RequestMapping("/orderSet")
    public Result orderSet(@RequestBody OrderSetting orderSetting) {
        System.out.println(orderSetting.getOrderDate() + "---" + orderSetting.getNumber());
        //调用update方法
        try {
            orderSettingService.edit(orderSetting);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
        return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
    }
}
